#include"sender.h"


using namespace std;






/***************************************
			Class Sender
***************************************/


Sender::Sender()
{
	sender_running = true;

	server_port = 8888;
	sender_running = true;
}

Sender::~Sender()
{
}


void
Sender::stop_sender()
{
	sender_running = false;
}



void
Sender::run_sender()
{

	preset_sender();
	start_sender();
	end_sender();
	close(client_fd);
	return ;
}

void 
Sender::preset_sender()
{
	client_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(client_fd<0)
	{
		ColorPrint::printRed("create socket fail!\n");
		return;	
	}
	
	memset(&ser_addr, 0, sizeof(ser_addr));
	ser_addr.sin_family = AF_INET;
	//ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	ser_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
	ser_addr.sin_port = htons(server_port);
}

void
Sender::start_sender()
{
	socklen_t len;
	struct sockaddr_in src;
	struct sockaddr* dst = (struct sockaddr*)&ser_addr;
	while(1)
	{
		if(sender_running==false)
		{
			//break;	
			ColorPrint::printRed("sender time out!\n");
			return ;
		}

		//char buf[BUFF_LINE] = "TEST UDP MSG!\n";
		set_header();
		memset(buf, 0, sizeof(buf));
		strcpy(buf, header);
		strcat(buf, "\n");
		strcat(buf, "TEST UDP MSG!\n");
		len = sizeof(*dst);
		ColorPrint::printGreen("SENDER>>\n");
		printf("%s\n", buf);
		sendto(client_fd, buf, BUFF_LINE, 0, dst, len);
		/*
		memset(buf, 0, BUFF_LINE);
		recvfrom(client_fd, buf, BUFF_LINE, 0, (struct sockaddr*)&src, &len);
		printf("SENDER>>server:%s\n", buf);
		*/
		sleep(1);
	}
	return ;
}

void
Sender::end_sender()
{
	socklen_t len;
	struct sockaddr_in src;
	struct sockaddr* dst = (struct sockaddr*)&ser_addr;
	//char buf[BUFF_LINE] = "END";
	set_header();
	memset(endbuf,0, sizeof(endbuf));
	strcpy(endbuf,header); 
	strcat(endbuf, "END");
	len = sizeof(*dst);
	ColorPrint::printGreen("SENDER>>\n");
	printf("%s\n", endbuf);
	sendto(client_fd, endbuf, BUFF_LINE, 0, dst, len);
	//memset(endbuf, 0, BUFF_LINE);
	//recvfrom(client_fd, endbuf, BUFF_LINE, 0, (struct sockaddr*)&src, &len);
	//printf("SENDER>>server:%s\n", endbuf);
	sleep(1);
}

void 
Sender::set_header()
{
	Clock clock;
	clock.click();
	memset(header, 0, sizeof(header));
	strcpy(header, clock.strTimeClicked);
}

/***************************************
			Class SenderController
***************************************/

Sender *SenderController::sender_ptr	= NULL;

void
SenderController::sender_install( Sender *sender )
{
	sender_ptr = sender ;
}
void
SenderController::sender_stop_sender()
{
	sender_ptr->stop_sender();
}

/***************************************
			Class SenderThread
***************************************/
SenderThread::SenderThread()
{
}

SenderThread::~SenderThread()
{
	if(t_sender != NULL)
	{
		delete(t_sender);	
		t_sender=NULL;
	}
}

void 
SenderThread::run_independent_sender()
{
	t_sender = new thread(&Sender::run_sender, &sender);
}
void 
SenderThread::wait_for_sender()
{
	t_sender->join();
}

